<template>
  <div class="cart">
    <h2>Your Cart</h2>
    <p v-show="!cartProducts.length">
      <i>Please add some products to cart.</i>
    </p>
    <ul>
      <li v-for="product in cartProducts" :key="product.id">
        {{ product.title }} - {{ product.price }} x {{ product.quantity }}
      </li>
    </ul>
    <p>{{cartTotalPrice}}</p>
    <p>
      <button :disabled="!cartProducts.length" @click="checkout(cartProducts)">
        Checkout
      </button>
    </p>
    <p v-show="checkoutStatus">Checkout {{ checkoutStatus }}.</p>
  </div>
</template>

<script>
  import { createNamespacedHelpers } from "vuex";

  const { mapState, mapActions ,mapGetters} = createNamespacedHelpers("cart");
  const { mapState: productMapState } = createNamespacedHelpers("product");

  export default {
    computed: {
      ...mapState({
        items: state => state.items,
        checkoutStatus: state => state.checkoutStatus
      }),
      ...productMapState({
        allProducts: state => state.all
      }),
      // cartProducts() {
      //   // 遍历 items，并修改数据
      //   return this.items.map(({ id, quantity }) => {
      //     const product = this.allProducts.find(product => product.id === id);
      //     // 通过 return 修改原始数据，把product 的名称和价格赋值给对象
      //     return {
      //       id,
      //       title: product.title,
      //       price: product.price,
      //       quantity
      //     };
      //   });
      // }
      ...mapGetters(["cartProducts","cartTotalPrice"]),
      
    },
    methods: {
      ...mapActions(["checkout"])
    }
  };
</script> 

<style lang="scss" scoped>

</style>